<template>
  <div class="visit-details">
    <div class="visit-details__left">
      <div class="visit-details__left-header">
        <el-select
          v-model="addType"
          placeholder="请选择"
          size="mini"
        >
          <el-option
            label="访问须知"
            :value="1"
          />
          <el-option
            label="详情规则"
            :value="2"
          />
        </el-select>
        <el-button
          size="mini"
          type="primary"
          icon="el-icon-plus"
          style="margin-left: 10px"
          @click="addRule"
        >
          添加
        </el-button>
      </div>

      <el-form ref="elFormRef" label-position="left" :model="formData">
        <div
          v-for="(item, index) in formData.content"
          :key="`content-${index}`"
          class="inline"
        >
          <el-divider>访客须知{{ index + 1 }}</el-divider>
          <div style="display: flex; justify-content: end; padding: 10px;">
            <i
              class="el-icon-close"
              style="font-size: 20px;"
              @click="deleteRule('content', index)"
            />
          </div>
          <el-form-item
            label="访客须知内容"
            label-width="110px"
            :prop="`content.${index}.content`"
            :rules="{
              required: true,
              message: '须知内容不能为空',
              trigger: ['blur', 'change'],
            }"
          >
            <el-input
              v-model="formData.content[index].content"
              placeholder="请填写访客须知"
            />
          </el-form-item>

          <el-form-item
            label="图标"
            label-width="110px"
            :prop="`content.${index}.icon`"
            :rules="{
              required: true,
              message: '图标不能为空',
              trigger: ['blur', 'change'],
            }"
          >
            <el-upload
              class="avatar-uploader"
              action="/api/v1/upload/file"
              :show-file-list="false"
              list-type="picture-card"
              :on-success="(e) => uploadIconSuccess(e, index)"
            >
              <img
                v-if="formData.content[index].icon"
                :src="formData.content[index].icon"
                class="avatar"
                alt="封面"
              >
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>
        </div>
        <el-divider />
        <div
          v-for="(item, index) in formData.ruleDetails"
          :key="`ruleDetails-${index}`"
        >
          <div style="display: flex; justify-content: flex-end; padding: 10px;">
            <i
              class="el-icon-close"
              style="font-size: 20px;"
              @click="deleteRule('ruleDetails', index)"
            />
          </div>
          <el-form-item
            :label="`规则详情-${index + 1}`"
            label-width="110px"
            :prop="`ruleDetails.${index}.content`"
            :rules="{
              required: true,
              message: '规则详情不能为空',
              trigger: ['blur', 'change'],
            }"
          >

            <el-input
              v-model="formData.ruleDetails[index].content"
              type="textarea"
              placeholder="请填写规则详情"
              :maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </div>

      </el-form>

      <div class="visit-details__left-footer">
        <el-button
          type="primary"
          size="small"
          :loading="loading"
          @click="validateForm"
        >
          {{ formData.ruleId ? '修改访客须知' : '创建访客须知' }}
        </el-button>
      </div>

    </div>
    <div class="visit-details__right">
      <Preview
        :visitor-notice="formData.content"
        :visitor-rules="formData.ruleDetails"
      />
    </div>
  </div>
</template>
<script>
import Preview from '@/views/visitRule/components/Preview.vue'
import { setVisitorRule, editVisitorRule, getVisitorRuleList } from '@/api/v2/visitor'
export default {
  name: '',
  components: {
    Preview
  },
  data() {
    return {
      formData: {
        ruleId: null,
        content: [{ icon: '', content: '' }],
        ruleDetails: [{ content: '' }]
      },
      addType: 1,
      loading: false
    }
  },
  created() {
    const { query } = this.$route
    this.formData.ruleId = query?.ruleId
    if (query?.ruleId) {
      this.getRuleDetails()
    }
  },
  methods: {

    async getRuleDetails() {
      try {
        const res = await getVisitorRuleList({ ruleId: this.formData.ruleId })
        console.log('res --------->', res)
        const { content, rule_details } = res.data
        this.formData.content = content
        this.formData.ruleDetails = rule_details
      } catch (error) {
        this.$message.error(error.response.data.message || '详情获取失败')
      }
    },

    uploadIconSuccess(e, index) {
      this.formData.content[index].icon = e.data.path
      this.validateField(`content.${index}.icon`)
    },

    validateField(field) {
      this.$refs.elFormRef.validateField(field)
    },

    addRule() {
      const type = {
        1: { icon: '', content: '' },
        2: { content: '' }
      }
      if (this.addType === 1) {
        if (this.formData.content.length >= 5) return this.$message.error('访客须知最多只能添加五条')
        this.formData.content.push(type[this.addType])
      } else {
        if (this.formData.ruleDetails.length >= 3) return this.$message.error('规则详情最多只能添加三条')
        this.formData.ruleDetails.push(type[this.addType])
      }
    },

    deleteRule(type, index) {
      this.$confirm('是否删除该项？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.formData[type].splice(index, 1)
      })
    },

    validateForm() {
      this.$refs.elFormRef.validate(flag => {
        console.log('flag --------->', flag)
        if (!flag) return this.$message.error('请将信息填写完整！')
        const data = this.paramsFormatter(this.formData)
        if (!this.formData.ruleId) {
          this.createVisitorRule(data)
        } else {
          this.editeVisitorRule(data)
        }
      })
    },

    async createVisitorRule(data) {
      this.loading = true
      try {
        const res = await setVisitorRule(data)
        console.log('res --------->', res)
        this.$message.success('创建成功')
        setTimeout(() => {
          this.back()
        }, 1000)
      } catch (error) {
        this.$message.error(error.response.data.message || '创建失败')
      } finally {
        this.loading = false
      }
    },

    async editeVisitorRule(data) {
      this.loading = true
      try {
        const res = await editVisitorRule(data)
        this.$message.success('修改成功')
        this.refresh()
      } catch (error) {
        this.$message.error(error.response.data.message || '修改失败')
      } finally {
        this.loading = false
      }
    },

    refresh() {
      this.getRuleDetails()
    },

    back() {
      this.$router.back()
    },

    paramsFormatter(data) {
      return {
        ...data,
        content: JSON.stringify(data.content),
        ruleDetails: JSON.stringify(data.ruleDetails)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.visit-details {
  //padding: 20px;
  display: flex;
  position: relative;

  &__left {
    width: 45%;
    padding: 20px;
    background-color: #fff;

    &-footer {
      display: flex;
      justify-content: flex-end;
    }

  }

  &__right {
    padding: 20px 230px;
    width: 55%;
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    background-color: #F2F5FA;
  }

  .inline {
    //display: flex;
  }
}

:deep(.avatar-uploader) {
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }
  .avatar {
    width: 148px;
    height: 148px;
    display: block;
  }
}

:deep(.el-divider--horizontal) {
  margin: 24px 0 10px 0;
}

</style>
